import JSEncrypt from 'jsencrypt'
//去密钥生成网址去生成公钥和密钥 http://tools.jb51.net/password/rsa_encode
var publicKey = '生成的公钥'
var privateKey ='生成的密钥'

/**
 * 最长加密长度
 */
const MAX_ENCRYPT_BLOCK = 10000 // 117
/**
 * 最长解码长度
 */
const MAX_DECRYPT_BLOCK = 10000 // 128

export function setPublicKey (key) {
  publicKey = key
}

export function setPrivateKey (key) {
  privateKey = key
}


export const encrypt = (data, publicKey, size = 1024) => {
  const jse = new JSEncrypt({
    default_key_size: size
  })
  jse.setPublicKey(
    `-----BEGIN PUBLIC KEY-----\n${publicKey}\n-----END PUBLIC KEY-----`
  )
  return jse.encrypt(data);
};

export const decrypt = (data, privateKey, size = 1024) => {
  const jse = new JSEncrypt({
    default_key_size: size
  })
  jse.setPrivateKey(
    `-----BEGIN PRIVATE KEY-----\n${privateKey}\n-----END PRIVATE KEY-----`
  )
  return jse.decrypt(data);
}

/**
 * @description RSA加密(支持长字符加密)
 */
export function encryptedData (data) {
  //创建实例
  const encrypt = new JSEncrypt()
  // 设置公钥
  encrypt.setPublicKey(
    `-----BEGIN PUBLIC KEY-----${publicKey}-----END PUBLIC KEY-----`
  )
  let bufTmp = ''
  let hexTmp = ''
  let result = ''
  const buffer = JSON.stringify(data)
  let offSet = 0
  const inputLen = buffer.length
  while (inputLen - offSet > 0) {
    if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
      bufTmp = buffer.slice(offSet, offSet + MAX_ENCRYPT_BLOCK)
    } else {
      bufTmp = buffer.slice(offSet, inputLen)
    }
    //对数据进行加密
    hexTmp = encrypt.encrypt(bufTmp.toString())
    result += hexTmp
    offSet += MAX_ENCRYPT_BLOCK
  }
  //js可以使用Buffer.from()  ts中使用Buffer.from()，运行后控制台会报错Buffer undefined所以使用替代方案node方法btoa再次加密
  return btoa(result)
}

/**
 * @description RSA解密(支持长字符解密)
 * @param data
 * @returns {PromiseLike<ArrayBuffer>}
 */
export function decryptedData (data) {
  const decrypt = new JSEncrypt()
  //设置私钥
  decrypt.setPrivateKey(
    `-----BEGIN RSA PRIVATE KEY-----${privateKey}-----END RSA PRIVATE KEY-----`
  )
  let bufTmp = ''
  let hexTmp = ''
  let result = ''
  //通过使用atob解码数据  如果使用的Buffer.from()使用Buffer.from()解码数据
  const buffer = atob(data)
  let offSet = 0
  const inputLen = buffer.length
  while (inputLen - offSet > 0) {
    if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
      bufTmp = buffer.slice(offSet, offSet + MAX_DECRYPT_BLOCK)
    } else {
      bufTmp = buffer.slice(offSet, inputLen)
    }
    //对数据解码
    hexTmp = decrypt.decrypt(bufTmp)
    result += hexTmp
    offSet += MAX_DECRYPT_BLOCK
  }
  return JSON.parse(result)
}

